package net.linku.interceptor;

import net.linku.exception.LinkUException;
import net.linku.utils.TenantContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TenantInterceptor 用于在每个请求开始时设置租户ID，并在请求结束时清理租户ID。
 */
@Component
public class TenantInterceptor implements HandlerInterceptor {

    private static final String TENANT_HEADER = "X-Tenant-ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 过滤掉 swagger-ui 的请求
        String uri = request.getRequestURI();
        if (uri.contains("/swagger-ui") || uri.contains("/v2/api-docs") || uri.contains("/swagger-resources") || uri.contains("/webjars")) {
            return true;
        }

        // 从请求头中获取租户ID，并设置到 TenantContext
        String tenantId = request.getHeader(TENANT_HEADER);

        if (StringUtils.isBlank(tenantId)) {
            throw new LinkUException("TENANT_ID_MISSING", "租户ID不能为空", "请求头中未包含租户ID");
        }

        TenantContext.setTenantId(tenantId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后清理租户ID
        TenantContext.clear();
    }
}
